﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DevComponents.DotNetBar;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

namespace IPR_TrainExamSys_TY
{
    public partial class FrmMain : Form
    {
        public FrmMain(Model.T_PublicEmployee curUser)
        {
            Common.JsonHepler jh = new Common.JsonHepler(); 

            InitializeComponent(); 
            initImageList();
            BaseClass.CLoginInfo.LoginEmployee = curUser;
            tsslCurUserName.Text = curUser.EmployeeName;
            try
            {
                superTabControlPanel1.BackgroundImage = Image.FromFile(Application.StartupPath + "\\imgbg.png");
                this.Text = BaseClass.CLoginInfo.Title;
                lbTitle.Text = BaseClass.CLoginInfo.Title;
            }
            catch
            {
            }
        }
        string sIconPath = Application.StartupPath + "\\icon\\";
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {

                #region 初始化菜单和功能栏
                string sWhere = " IsUse=1 ";
                sWhere += getPowerStr();//2018-12-26 宋金明 add
                DataSet dsFun = new T_Function().GetList(sWhere);
                if (dsFun != null)
                {
                    if (dsFun.Tables.Count > 0)
                        if (dsFun.Tables[0].Rows.Count > 0)
                        {
                            //菜单自定义增加
                            DataRow[] dr = dsFun.Tables[0].Select(" ParentFunID='' and LevelID=1 ", " FunID ASC");
                            for (int i = 0; i < dr.Count(); i++)
                            {
                                ButtonItem bi = new ButtonItem(dr[i]["FunID"].ToString(), dr[i]["FunName"].ToString() + "(&" + dr[i]["Abbreviation"].ToString() + ")");
                                SideBarPanelItem sbpi = new SideBarPanelItem(dr[i]["FunID"].ToString(), dr[i]["FunName"].ToString());
                                AddMenu(bi, dsFun, dr[i]["FunID"].ToString());
                                barMenu.Items.Insert(i, bi);

                                AddSide(sbpi, dsFun, dr[i]["FunID"].ToString());
                                sideBar1.Panels.Add(sbpi);


                                AddToolBar(dsFun, dr[i]["FunID"].ToString());

                            }
                            if (sideBar1.Panels.Count > 0)
                                sideBar1.Panels[0].Expanded = true;
                        }
                }
                #endregion
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "错误");
            }
        }
        /// <summary>
        /// 得到对应权限模块
        /// </summary>
        /// <returns></returns>
        private string getPowerStr()
        {
            string powerstr="";
            string strClassGrop = BaseClass.CLoginInfo.LoginEmployee.ClassGroup.Trim();
            string strWorkShop = BaseClass.CLoginInfo.LoginEmployee.WorkShop.Trim();
            if (null != strClassGrop && strClassGrop != "")
            {
                powerstr = new BLL.T_DepPower().getPowerByDepName(strClassGrop);
            }
            else if (null != strWorkShop && strWorkShop != "")
            {
                powerstr= new BLL.T_DepPower().getPowerByDepName(strWorkShop);
            }
            powerstr = " and funid in ('" + powerstr.Replace(",","','")+"') ";
            return powerstr;
        }

        /// <summary>
        /// 初始化所有的图标，使用动态初始化方便以后自己更新图标
        /// 更新时如果图标名称变化时需要同时更新数据库
        /// </summary>
        private void initImageList()
        {
            imageList1.ImageSize = new Size(64, 64);
            string[] files = Directory.GetFiles(sIconPath);
            for (int i = 0; i < files.Length; i++)
            {
                imageList1.Images.Add(files[i].Substring(files[i].LastIndexOf("\\")+1), Image.FromFile(files[i]));
            }
        }
        /// <summary>
        /// 添加对应的菜单项
        /// </summary>
        /// <param name="bi"></param>
        /// <param name="dsFun"></param>
        /// <param name="FunID"></param>
        private void AddMenu(ButtonItem bi, DataSet dsFun, string FunID)
        {
            try
            {
                DataRow[] dr = dsFun.Tables[0].Select(" ParentFunID='" + FunID + "' ", " FunID ASC");
                if (dr.Count() > 0)
                {
                    for (int i = 0; i < dr.Count(); i++)
                    {
                        ButtonItem bsubi = new ButtonItem(dr[i]["FunID"].ToString(), dr[i]["FunName"].ToString());
                        if (dr[i]["FrmCode"].ToString() != "")
                            bsubi.Description = dr[i]["FrmCode"].ToString();
                        bsubi.Click += bsubi_Click;
                        AddMenu(bsubi, dsFun, dr[i]["FunID"].ToString());
                        bi.SubItems.Add(bsubi);
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "菜单项添加失败");
            }
        }


        /// <summary>
        /// 添加对应的菜单项
        /// </summary>
        /// <param name="bi"></param>
        /// <param name="dsFun"></param>
        /// <param name="FunID"></param>
        private void AddToolBar( DataSet dsFun, string FunID)
        {
            try
            {
                DataRow[] dr = dsFun.Tables[0].Select(" ParentFunID='" + FunID + "' ", " FunID ASC");
                if (dr.Count() > 0)
                {
                    for (int i = 0; i < dr.Count(); i++)
                    {
                        ButtonItem bsubi = new ButtonItem(dr[i]["FunID"].ToString(), dr[i]["FunName"].ToString());
                        if (dr[i]["FrmCode"].ToString() != "")
                            bsubi.Description = dr[i]["FrmCode"].ToString();
                        if (dr[i]["IcoName"].ToString() != "")
                        {
                            Bitmap bm = new Bitmap(imageList1.Images[dr[i]["IcoName"].ToString()], new Size(20, 20));
                            Icon ic = Icon.FromHandle(bm.GetHicon());
                            bsubi.Icon = ic;
                            bsubi.ButtonStyle = eButtonStyle.Default;
                        }

                        if (dr[i]["FrmCode"].ToString() != "")
                            bsubi.Description = dr[i]["FrmCode"].ToString();
                        bsubi.Tooltip = dr[i]["FunName"].ToString();
                        bsubi.Click += bsubi_Click;
                        bar2.Items.Add(bsubi);

                        Application.DoEvents();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "工具项添加失败");
            }
        }

        /// <summary>
        /// 添加功能菜单模块
        /// </summary>
        /// <param name="bi"></param>
        /// <param name="dsFun"></param>
        /// <param name="FunID"></param>
        private void AddSide(SideBarPanelItem bi, DataSet dsFun, string FunID)
        {
            try
            {
                DataRow[] dr = dsFun.Tables[0].Select(" ParentFunID='" + FunID + "' ", " FunID ASC");
                if (dr.Count() > 0)
                {
                    for (int i = 0; i < dr.Count(); i++)
                    {
                        ButtonItem bsubi = new ButtonItem(dr[i]["FunID"].ToString(), dr[i]["FunName"].ToString());
                        bsubi.ButtonStyle = eButtonStyle.ImageAndText;
                        bsubi.ImagePosition = eImagePosition.Top;
                        if (dr[i]["FrmCode"].ToString() != "")
                            bsubi.Description = dr[i]["FrmCode"].ToString();
                        if (dr[i]["IcoName"].ToString() != "")
                            bsubi.Image = imageList1.Images[dr[i]["IcoName"].ToString()];
                        if (dr[i]["FrmCode"].ToString() != "")
                            bsubi.Description = dr[i]["FrmCode"].ToString();
                        bsubi.Click += bsubi_Click;
                        bi.SubItems.Add(bsubi);
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "功能栏添加失败");
            }
        }

         
        IntPtr appWin;
        
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
            CharSet = CharSet.Unicode, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
        private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
        private static extern long GetWindowLong(IntPtr hwnd, int nIndex);

        [DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
        private static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong);
        //private static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        private static extern bool PostMessage(IntPtr hwnd, uint Msg, long wParam, long lParam);
        private const int SWP_NOOWNERZORDER = 0x200;
        private const int SWP_NOREDRAW = 0x8;
        private const int SWP_NOZORDER = 0x4;
        private const int SWP_SHOWWINDOW = 0x0040;
        private const int WS_EX_MDICHILD = 0x40;
        private const int SWP_FRAMECHANGED = 0x20;
        private const int SWP_NOACTIVATE = 0x10;
        private const int SWP_ASYNCWINDOWPOS = 0x4000;
        private const int SWP_NOMOVE = 0x2;
        private const int SWP_NOSIZE = 0x1;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 0x10000000;
        private const int WM_CLOSE = 0x10;
        private const int WS_CHILD = 0x40000000;
 



        void bsubi_Click(object sender, EventArgs e)
        {
            try
            {
                ButtonItem biClick = (ButtonItem)sender;
                if (biClick.Description != "")
                {
                    string sFrmCode = biClick.Description.Substring(0, biClick.Description.Length - 3).Replace('\\', '.');//数据库中存储路径含后缀名
                    string strnamespace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;//根据你自己的命名空间来修改
                    Form frm = (Form)Assembly.Load(strnamespace).CreateInstance(strnamespace + sFrmCode);
                    if (frm != null) SetMdiForm(biClick.Text, frm.GetType());
                    else
                    {
                         

                        #region 直接启动对应的EXE文件,并不嵌入到WinForm窗体中，当前不适用



                        //System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(Application.StartupPath + "\\OnlineExamZZ.exe");
                        //if (processes.Length < 1)
                        //{
                        //    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\OnlineExamZZ.exe");
                        //    startInfo.Arguments = "TFrmQryExam -1  3002031  passWord 0 苏小凡 3002031 userDept ";

                        //    System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
                        //    //this.Thread.

                        //    if (process != null)
                        //    {
                        //        process.WaitForExit();

                        //    }
                        //    startInfo = null;
                        //}
                        //processes = null;
                        #endregion 
                         



                        string exeName = Application.StartupPath + "\\OnlineExamZZ.exe";
                        try
                        {
                            // Start the process
                            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\OnlineExamZZ.exe");
                            startInfo.Arguments = "TFrmQryExam -1  3002031  passWord 0 苏小凡 3002031 userDept ";
                            System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);

                            // Wait for process to be created and enter idle condition
                            process.WaitForInputIdle();
                            // Get the main handle
                            appWin = process.MainWindowHandle;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(this, ex.Message, "Error");
                        }
                        // Put it into this form
                        SetParent(appWin, this.Handle);
                        // Remove border and whatnot
                        // SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE);
                        // Move the window to overlay it on this window
                        MoveWindow(appWin, 0, 0, this.Width, this.Height, true);
                        
                        //if (frmNew != null) SetMdiForm(biClick.Text, frmNew.GetType());
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "功能打开失败");

            }
        }



        [DllImport("shell32.dll")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);




















        /// <summary>
        /// 创建或者显示一个多文档界面页面
        /// </summary>
        /// <param name="caption">窗体标题</param>
        /// <param name="formType">窗体类型</param>
        public void SetMdiForm(string caption, Type formType)
        {
            bool IsOpened = false;

            //遍历现有的Tab页面，如果存在，那么设置为选中即可
            foreach (SuperTabItem tabitem in NavTabControl.Tabs)
            {
                if (tabitem.Name == caption)
                {
                    NavTabControl.SelectedTab = tabitem;
                    IsOpened = true;
                    break;
                }
            }

            //如果在现有Tab页面中没有找到，那么就要初始化了Tab页面了
            if (!IsOpened)
            {
                //为了方便管理，调用LoadMdiForm函数来创建一个新的窗体，并作为MDI的子窗体
                //然后分配给SuperTab控件，创建一个SuperTabItem并显示
                //DevComponents.DotNetBar.Office2007Form form = ChildWinManagement.LoadMdiForm(this, formType)
                //    as DevComponents.DotNetBar.Office2007Form;
                Form form = ChildWinManagement.LoadMdiForm(this, formType);
                SuperTabItem tabItem = NavTabControl.CreateTab(caption);
                tabItem.Name = caption;
                tabItem.Text = caption;
                form.TopLevel = false;
                form.Visible = true;
                form.Dock = DockStyle.Fill;
                form.FormClosing += form_FormClosing;
                form.Name = caption;

                if (caption == "试题管理")
                {
                    System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(Application.StartupPath + "\\OnlineExamZZ.exe");
                    if (processes.Length < 1)
                    {
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\OnlineExamZZ.exe");
                        startInfo.Arguments = "TFrmTopicAll 0 " + BaseClass.CLoginInfo.LoginEmployee.EmployeeId + "  " + BaseClass.CLoginInfo.LoginEmployee.Password + " 0 " + BaseClass.CLoginInfo.LoginEmployee.EmployeeName + " " + BaseClass.CLoginInfo.LoginEmployee + " " + BaseClass.CLoginInfo.LoginEmployee.WorkShop + " " + form.Handle.ToString();

                        System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);

                        startInfo = null;
                    }
                    processes = null;
                }
                else if (caption == "试卷管理")
                {
                    System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(Application.StartupPath + "\\OnlineExamZZ.exe");
                    if (processes.Length < 1)
                    {
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\OnlineExamZZ.exe");
                       // startInfo.Arguments = "TFrmTopicAll -1  3002031  passWord 0 苏小凡 3002031 userDept " + form.Handle.ToString();
                        startInfo.Arguments = "TFrmTopicAll 1 " + BaseClass.CLoginInfo.LoginEmployee.EmployeeId + "  " + BaseClass.CLoginInfo.LoginEmployee.Password + " 0 " + BaseClass.CLoginInfo.LoginEmployee.EmployeeName + " " + BaseClass.CLoginInfo.LoginEmployee + " " + BaseClass.CLoginInfo.LoginEmployee.WorkShop + " " + form.Handle.ToString();
                        System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);

                        startInfo = null;
                    }
                    processes = null;
                }
                else if (caption == "试题练习")
                {
                    System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(Application.StartupPath + "\\OnlineExamZZ.exe");
                    if (processes.Length < 1)
                    {
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\OnlineExamZZ.exe");
                        startInfo.Arguments = "TFrmTrain -1  3002031  passWord 0 苏小凡 3002031 userDept " + form.Handle.ToString();

                        System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);

                        startInfo = null;
                    }
                    processes = null;
                }

                //int a = ShellExecute(form.Handle, new StringBuilder("Open"), new StringBuilder("OnlineExamZZ.exe"), new StringBuilder("TFrmQryExam -1  3002031  passWord 0 苏小凡 3002031 userDept " + this.Handle.ToString()), new StringBuilder(Application.StartupPath + "\\"), 1);
                //System.Windows.Forms.MessageBox.Show(a.ToString());



                //tabItem.Icon = form.Icon;
                tabItem.AttachedControl.Controls.Add(form);

                NavTabControl.SelectedTab = tabItem;
            }
        }

        void form_FormClosing(object sender, FormClosingEventArgs e)
        {
            NavTabControl.SelectedTab.Close();
        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            string strnamespace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;//根据你自己的命名空间来修改
            string strfrm = ".DevInfo.FrmDevInfo.cs";
            strfrm = strfrm.Substring(0, strfrm.Length - 3);
            Form frm = (Form)Assembly.Load(strnamespace).CreateInstance(strnamespace + strfrm);
            
            SetMdiForm("设备信息1",frm.GetType());
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            tsslCurTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        public void CloseAllDocuments()
        {
            for (int i = NavTabControl.Tabs.Count - 1; i > 0; i--)
            {
                SuperTabItem tabitem = NavTabControl.Tabs[i] as SuperTabItem;
                if (tabitem != null)
                {
                    tabitem.Close();
                }
            }
        }

        public void CloseOthers()
        {
            if (ActiveMdiChild != null)
            {
                Type formType = ActiveMdiChild.GetType();
                for (int i = NavTabControl.Tabs.Count - 1; i > 0; i--)
                {
                    SuperTabItem tabitem = NavTabControl.Tabs[i] as SuperTabItem;
                    if (tabitem != null && formType != tabitem.AttachedControl.Controls[0].GetType())
                    {
                        tabitem.Close();
                    }
                }
            }
        }

        private void buttonItem3_Click(object sender, EventArgs e)
        {
            CloseAllDocuments();
        }

        private void buttonItem5_Click(object sender, EventArgs e)
        {
            CloseOthers();
        }

        private void 关闭所有窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseAllDocuments();
        }

        private void 除此之外全部关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseOthers();
        }

        private void NavTabControl_TabItemClose(object sender, SuperTabStripTabItemCloseEventArgs e)
        {
             
            //Type ty= ((SuperTabItem)sender).ContainerControl.GetType();
            //if (ty == typeof(Form))
            //Control[] con = NavTabControl.SelectedTab.AttachedControl.Controls.Find("试题文档导入", true);
            //Form frm = (Form)con[0];
            //frm.Close();
            //Control[] con1 = NavTabControl.Controls.Find(((SuperTabControl)sender).SelectedTab.Name, true);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            KillProcess("OnlineExamZZ");
        }
        private void KillProcess(string processName)
        {
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程   
            try
            {
                foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
                {
                    //找到程序进程,kill之。
                    if (!thisproc.CloseMainWindow())
                    {
                        thisproc.Kill();
                    }
                }

            }
            catch (Exception Exc)
            {
                MessageBox.Show(Exc.Message);
            }
        }

        private void biClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 关于本系统_Click(object sender, EventArgs e)
        {
            FrmAbout frma = new FrmAbout();
            frma.ShowDialog();
            frma.Close();
        }

        private void 系统帮助_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\操作说明书.doc");
            System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
        }

    }
}
